<template>
  <div class="flowChart">
    <!--<a-layout-header style="background-color:#0B0121; padding: 0">
      <span style="color: #ffffff ;opacity: 0.87">
        线路号/列车号  &nbsp:&nbsp
      </span>
      &lt;!&ndash; 下拉框 &ndash;&gt;
      <a-cascader
          style="background-color: #0B0121; color: #ffffff ;opacity: 0.87"
          v-model:value="trainInfo.trains"
          :options="trainInfo.lines"
          expand-trigger="hover"
          :display-render="displayRender"
          @change="onLineChange"
      />
    </a-layout-header>-->
    <a-layout id="components-layout-demo-side" style="min-height: 100vh">

      <a-layout-sider v-model="collapsed" collapsedWidth="0" collapsible>
     <!--   <span style="color: #ffffff ;opacity: 0.87; padding-left: 20px">
        线路 &nbsp
        </span>
        &lt;!&ndash; 下拉框 &ndash;&gt;
        <a-cascader
                class="myHead"
                style=" color: #ffffff ;opacity: 0.87;width: 120px"
                v-model:value="trainInfo.trains"
                :options="trainInfo.lines"
                expand-trigger="hover"
                :display-render="displayRender"
                @change="onLineChange"
        />-->
        <span style="color: #ffffff ;opacity: 0.87; padding-left: 20px; padding-right: 8px">
        车号
        </span>
        <!-- 下拉框 -->
        <a-cascader
                class="myHead"
                style=" color: #ffffff ;opacity: 0.87;width: 120px;"
                v-model:value="trainInfo.trains"
                :options="trainInfo.lines"
                :display-render="displayRender"
                placeholder="请选择"
                expand-trigger="hover"
                @change="onLineChange"
        />
        <br>
        <!-- 搜索框 -->
        <a-input-search
                class="myHead"
                v-model:value="searchValue"
                style="margin-bottom: 8px;margin-left: 20px;padding-right: 20px;width: 90%"
                placeholder="关键词搜索" @change="onChange"
        />
<!--        树状结构-->
        <a-tree
            id="myTree"
            style="width: 100%;"
            :dropdown-style="{ maxHeight: '400px', overflow: 'hidden' }"
            :tree-data="treeData"
            placeholder="Please select"
            @select="selectnode"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            @expand="onExpand"
        >

          <template slot="title" slot-scope="{ title }">
          <span v-if="title.indexOf(searchValue) > -1">
            <span :title="title">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span style="color: rgba(255,0,0,1)">{{ searchValue }}</span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
          </span>
              <span v-else>
            <span :title="title">{{ title }}</span>
          </span>
          </template>
        </a-tree>
      </a-layout-sider>

          <!--  -->
          <a-layout-content style="margin-left: 16px;margin-right: 16px;background-color: #13192C">
            <a-layout-header id="layout-header">
              <span style="font-size: 16px;opacity: 0.87;float: left">应急处置建议</span>
              <span id="switchText" style="font-size: 14px;opacity: 0.6;float: right;margin-top: 4px">应急处理已打开</span>
              <a-switch
                      id="mySwitch"
                      v-model:checked="diagramClean"
                      size="middle"
                      @change="switchChange"
              />
            </a-layout-header>
<!--            中间画布，画流程图-->
              <canvas id="myCanvas" style="background-color:#13192C;display:block;margin:0 auto;">
                <a-modal v-model:visible="msgShow" :title="diagramName">
                  <p>{{nodeInfo.content}}</p>
                  <template #footer >
                    <a-button type="primary" @click="chooseStatus(true)">是</a-button>
                    <a-button type="primary"  @click="chooseStatus(false)">否</a-button>
                  </template>
                </a-modal>
              </canvas>
          </a-layout-content>

          <a-layout-sider width="300px">
            <!--            -->
            <!--<a-card style="background-color:#0B0121; border-color: #0B0121;"></a-card>-->
            <a-card style="background-color: #13192C; border-color: #131823;height: 63px;
                           border-bottom-color: #1C284B;padding-bottom: -12px;">
              <img src="@/assets/png/司机管理.png" style="padding-bottom: 5px" >&nbsp&nbsp
              <span style="color: #ffffff ;opacity: 0.87; font-size: 16px;">司机操作</span>
            </a-card>
            <br>
            <a-timeline style="background-color: #13192C; font-size: 14px;">
              <a-timeline-item v-for="(item) in opTimeline">
                <span style="color: #ffffff; opacity:0.60; margin-left: 10px;">{{item.operateTime}}</span>
                <span style="color: #2EA2F8;border: 1px solid #153E67 ;padding: 5px 5px 5px 8px;margin-left: 10px;border-radius: 5px;line-height: 20px" >{{item.operateDescr}}</span>
              </a-timeline-item>
            </a-timeline>
          </a-layout-sider>

    </a-layout>

  </div>
</template>

<style>
.myHead{
  margin-top: 16px;
  background-color: #13192C;
}
/**应急开关switch样式**/
.ant-layout-content .ant-switch {
  background-color: gray;
  color: #fff;
  opacity: 0.87;
  float: right;
  margin-top: 24px;
  margin-right: 8px;
}
.ant-layout-content .ant-switch-checked {
  background-color: #36AF47;
}
/**下拉框样式**/
.ant-cascader-menu{
  background-color: #171F37;
  color: rgba(255,255,255,0.87);
  width: 120px;
  border-right: 1px rgba(85,100,255,0.8) solid;
}
.ant-cascader-menu::-webkit-scrollbar {
  display: none;
}
.ant-layout-sider-children .ant-cascader-input {
  width: 100%;
  border-color: #1C346E ;
  background: #171F37 !important;
}
/*一级子菜单选中颜色*/
.ant-cascader-menu .ant-cascader-menu-item-active:not(.ant-cascader-menu-item-disabled) {
  background: linear-gradient(to right, rgba(24, 124, 255, 0.05) 0%,
  rgba(24, 124, 255, 0.48) 98%, rgba(24, 124, 255, 1)98%, rgba(24, 124, 255, 1)100%);
  color: white;
}
/*一级子菜单悬停颜色*/
.ant-cascader-menu .ant-cascader-menu-item-active:not(.ant-cascader-menu-item-disabled):hover {
  background-color: transparent;
}
/*二级子菜单悬停颜色*/
.ant-cascader-menu .ant-cascader-menu-item:hover {
  background: linear-gradient(to right, rgba(24, 124, 255, 0.05) 0%,
  rgba(24, 124, 255, 0.48) 98%, rgba(24, 124, 255, 1)98%, rgba(24, 124, 255, 1)100%);
}
.ant-cascader-picker-clear{
  color: white;
  background-color: #171F37;
}
.ant-cascader-picker-clear:hover {
  color: #55A0FF;
}
.ant-cascader-picker-arrow {
  color: white;
}
.ant-cascader-picker-arrow:hover {
  color: #55A0FF;
}

/**搜索栏样式**/
.ant-input-affix-wrapper .ant-input{
  background-color: #171F37;
  color: #ffffff;
  opacity: 0.87;
  border-color: #1C346E;
  padding-right: 20px;
}
.ant-input-affix-wrapper .ant-input:hover{
  border-color: #55A0FF;
}
.ant-input-affix-wrapper .ant-input-search-icon{
  color: #ffffff;
  margin-right: 16px;
}
.ant-input-affix-wrapper .ant-input-search-icon:hover{
  color: #55A0FF;
}
/**树样式**/
/*一级节点悬停高亮*/
/*li .ant-tree-node-content-wrapper .ant-tree-node-content-wrapper-normal:hover {
  background-color: #55A0FF;
}*/
/*一级节点悬停背景色*/
/*li.ant-tree-treenode-switcher-close:hover {
  background-color: #55A0FF;
  color: white;
}*/
/*二级节点悬停背景色*/
/*li .ant-tree-treenode-switcher-open:hover {
  background-color: #55A0FF;
}*/
.ant-tree li span.ant-tree-switcher.ant-tree-switcher-noop{
  width: 10px;
}
li .ant-tree-treenode-switcher-open{
  border-left: 1px rgba(255,255,255,0.1) solid;
}
li .ant-tree-treenode-switcher-close{
  border-left: 1px rgba(255,255,255,0.1) solid;
}
/*一级节点字体大小*/
.ant-layout .ant-tree  {
  font-size: 16px;
}
/*二级节点字体大小*/
.ant-tree ul {
  font-size: 14px;
}
/*全局节点文本框选中高亮*/
.ant-layout .ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected {
  color: white;
  opacity: 0.87;
  background: transparent;
  padding-left: 3px;
}
/*全局字体色*/
.ant-layout .ant-tree li .ant-tree-node-content-wrapper {
  color: rgba(255,255,255,0.37);
}
.ant-tree-treenode-switcher-open .ant-tree-treenode-selected {
  border-color: #55A0FF;
  background: linear-gradient(to right, rgba(24, 124, 255, 0.05) 0%,
  rgba(24, 124, 255, 0.48) 98%, rgba(24, 124, 255, 1)98%, rgba(24, 124, 255, 1)100%);
}
/*节点内框悬停背景色*/
.ant-layout .ant-tree li .ant-tree-node-content-wrapper:hover {
  background: transparent;
}
/*!*全局节点内框悬停背景色*!
.ant-tree-title:hover {
  background-color: #13192C;
}*/
/*树左侧标签颜色*/
#myTree{
  color: rgba(255,255,255,0.37);
  line-height: 30px;
}
/*树隐藏按键颜色及背景色*/
.ant-layout-sider .ant-layout-sider-trigger{
  background: linear-gradient(to right, rgba(24, 124, 255, 0.05) 0%,
  rgba(24, 124, 255, 0.48) 98%, rgba(24, 124, 255, 1)98%, rgba(24, 124, 255, 1)100%);
  color: rgba(24, 124, 255, 1);
}
/*画布顶边栏样式*/
.ant-layout-header{
  margin: 0 auto;
  background-color: #13192C;
  height: 62px;
  border-bottom:1px #1D397B solid;
}
#components-layout-demo-side .logo {
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  margin: 16px;
}
#components-layout-demo-basic .ant-layout-sider {
  background: #3ba0e9;
  color: #fff;
  line-height: 120px;
}
#components-layout-demo-basic .ant-layout-content {
  background: rgba(16, 142, 233, 1);
  color: #fff;
  min-height: 120px;
  line-height: 120px;
}

.ant-timeline-item-content{
  /*color: white;*/
}
.a-timeline-item{
  background-color: aquamarine;
}

/*.ant-layout-sider-children, .ant-layout-header{
  background-color: white;
}*/

/*侧边栏背景*/
.ant-layout-sider-children {
  background-color: #13192C;
}

/*主背景*/
.ant-layout-content{
  background-color: #0B1021;
  color: white;
}
.ant-layout-sider{
  overflow: hidden;
}
.ant-layout {
  background-color: transparent;
}

a-layout-sider .ant-timeline-item .ant-timeline-item-content{
  top: 0px;
  background: #70a3b8;
}
/*司机操作时间轴样式*/
.ant-timeline-item-head-blue {
  margin-left: 10px;
  background-color: #2EA2F8;
  width: 10px;
  height: 10px;
}
.ant-timeline-item-tail {
  margin-left: 10px;
  border-left: 2px solid #374264;
}
</style>

<script>
import axios from 'axios';

import {
  initCanvas,
  updateElements,
  drawElements,
  clearDraw,
  getClickNode,
} from "@/utils/RealTimeMonitoring/FlowChart";

function treeItem(title, value) {
  this.title = title;
  this.key = value;
  // this.selectable = false;
  this.children = [];
}
function treeChildren(title, value, status=false) {
  this.title = title;
  this.key = value;
  this.diagramOpen = status;
  this.diagramClean = true;
}

let dataList = [];
function generateList (data) {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: node.title });
    if (node.children) {
      generateList(node.children);
    }
  }
};

function getParentKey (key, tree) {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

function getFirstchildrenKey (key, tree) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.key === key && node.children.length > 0) {
      return node.children[0].key;
    }
  }
};

function getDiagramStatus (key, tree) {
  for (let i = 0 ; i < tree.length; i++){
    for (let j = 0; j < tree[i].children.length; j++){
      if (tree[i].children[j].key === key){
        return {
          open: tree[i].children[j].diagramOpen,
          clean: tree[i].children[j].diagramClean
        };
      }
    }
  }
  return false;
};

function setDiagramStatus (key, status, tree, clean) {
  for (let i = 0 ; i < tree.length; i++){
    for (let j = 0; j < tree[i].children.length; j++){
      if (tree[i].children[j].key === key){
        tree[i].children[j].diagramOpen = status;
        tree[i].children[j].diagramClean = clean;
        return;
      }
    }
  }
  return;
};


export default {
  name: "FlowChart",
  props:{
    displayRender: {
        type :Function,
        default : ({labels, selectedOptions}) => {
        return labels[labels.length - 1];
      }
    },
  },
  data() {
    return {
      timer: null,
      nodes: [],
      edges: [],
      index : 0,
      diagramName: "",
      msgShow : false,
      diagramOpen: false,
      diagramClean: true,
      nodeInfo: {
        nodeId: 0,
        content: ""
      },
      systems: {},
      treeRootkeyBase : 100,
      collapsed: false,//antd组件参数
      value: undefined,//树组件参数
      treeData: [],//树组件参数
      opTimeline: [],
      searchValue: "",
      expandedKeys: [],
      trainInfo: {
        lines: [],
        trains:[]
      },
      autoExpandParent: true,
      urlBase : process.env.VUE_APP_BASE_URL || "http://119.23.127.239:3333/phm-web-service-gz/"
    }
  },
  computed: {
    drawElem() {
      const {nodes, edges} = this
      return {
        nodes,
        edges
      }
    }
  },
  watch: {
    drawElem: function (){
      let canvas = initCanvas("myCanvas",1500,2500);
      updateElements(this.nodes, this.edges, canvas);
      drawElements(canvas);
    },
    treeData(value) {
      dataList = [];
      generateList(value);
    },
    diagramOpen(value){
      setDiagramStatus(this.index, value, this.treeData, true);
      this.diagramClean = true;
    }
  },
  methods: {
    //切换switch改变文本
    switchChange(checked) {
          this.checked = checked;
          let res = document.getElementById('switchText');
          if (this.checked) {
              res.innerText = '应急处理已打开';
          }
          else {
              res.innerText = '应急处理已关闭';
          }
    },
    //获取线路目录
    getTrainList: function () {
      let that = this;
      let url = this.urlBase + 'line/ganged?lineCode';
      this.trainInfo.lines = [];
      this.trainInfo.trains = [];
      axios.get(url,{
        params: "lineCode",
      }).then(function (resp) {
        if (resp.data != null)
        {
          that.trainInfo.lines = resp.data.result;
          that.trainInfo.trains.push(that.trainInfo.lines[0].value);
          that.trainInfo.trains.push(that.trainInfo.lines[0].children[0].value);
          //获取流程图目录
          that.getDiagramList();
        }
      })
      .catch(function (error)
      {
        console.log(error)
      });//请求出现错误时回调函数
    },
    //获取流程图目录
    getDiagramList: function () {
      let that = this;
      //需修改为后端地址
      let url = this.urlBase + 'base/system/dict';
      //根节点的key
      let rootKey = this.treeRootkeyBase;
      axios.get(url,{
        params:{
          dictType : "system_code_esc"
        }
      }).then(function (resp) {
        if (resp.data != null)
        {    //生成父节点
          that.treeData = [];
          that.systems = resp.data.result;
          let line = that.trainInfo.trains[0];
          let train = that.trainInfo.trains[1];
          let systemUrl = that.urlBase + 'emergency/emergy_lists';
          axios.get(systemUrl,{
            params: {
              "lineCode": line,
              "trainCode": train,
              // "systemCode": system,//标准的子系统编码
              // "sceneCode":"1001",	//非必须  从首页 进来时 带上 }
            }
          }).then(function (resp) {
            if (resp.data != null && resp.data.result != null)
            {
                for (let key in that.systems) {
                  let tItem = new treeItem(key, that.systems[key]);
                  for (let i = 0; i < resp.data.result.length; i++)
                  {
                    let item = resp.data.result[i];
                    if (item.system === key){
                      let cItem = new treeChildren(item["sceneName"], item["sceneCode"]);
                      tItem.children.push(cItem);
                    }
                  };
                  that.treeData.push(tItem);
                }
              }
            });
            that.diagramOpen = false;
            that.diagramClean = true;
            that.expandedKeys = [];
          }
        }
      )
        .catch(function (error)
        {//点击系统时做的操作，如点击“制动系统”、“车门系统”
          //需清空画布
          clearDraw();
          console.log(error)
        });//请求出现错误时回调函数
    },
    onLineChange: function (key) {
      this.trainInfo.line = key[0];
      this.trainInfo.train = key[1];
      this.getDiagramList();
    },
    getFlowChartData: function (key, name) {
      let that = this;
      let url = this.urlBase;
      let params = {
        sceneCode : key,
      };
      if (this.diagramOpen){
        url = url + 'emergency/emergy_proccess_detail';
        params["lineCode"] = this.trainInfo.trains[0];
        params["trainCode"] = this.trainInfo.trains[1];
        params["isClean"]= this.diagramClean === true ? 1 : 0;
      }else{
        url = url + 'emergency/emergy_detail';
        params["screenName"] = name;
      }
      axios.get(url,{
        params
      }).then(function (resp) {
        if (that.diagramOpen){
          setDiagramStatus(key,that.diagramOpen,that.treeData, false);
          that.diagramClean = false;
        }
        that.nodes = resp.data.result.images[0].nodes;
        that.edges = resp.data.result.images[0].edges;
      })
      .catch(function (error)
      {//点击系统时做的操作，如点击“制动系统”、“车门系统”
        //需清空画布
        clearDraw();
        console.log(error)
      });//请求出现错误时回调函数
    },
    drawFlowChart: function (key, name) {
      //清空画布
      clearDraw();
      //根据子节点的key，也就是流程图id，从后端获取节点数据
      this.getFlowChartData(key, name);
      this.index = key;
      this.diagramName = name;
    },
    selectnode: function (selectedKeys, info){
      //是父节点，选中父节点则将该父目录展开或关闭
      for(let key in this.systems){
        if (info.node.eventKey === this.systems[key]) {
          let flag = false;
          this.autoExpandParent = true;
          for (let i = 0; i < this.expandedKeys.length; i++){
            let pKey = getParentKey(this.expandedKeys[i],this.treeData);
            // 如果有子节点在expandedKeys里，说明已展开，则将关闭
            if (this.expandedKeys[i] == info.node.eventKey ||
                (pKey == info.node.eventKey)){
              this.expandedKeys.splice(i,1);
              flag = true;
            }
          }
          // 没有子节点在expandedKeys里，说明未展开，则将其展开
          if (flag == false){
            let cKey = getFirstchildrenKey(info.node.eventKey,this.treeData);
            this.expandedKeys.push(cKey);
          }
          return;
        }
      }
      let diagramStatus = getDiagramStatus(info.node.eventKey, this.treeData);
      //选中子节点则开始画图
      this.diagramOpen = diagramStatus.open;
      this.diagramClean = diagramStatus.clean;
      this.opTimeline = [];
      this.drawFlowChart(info.node.eventKey,info.node.dataRef.title);
    },
    // 历史操作栏
    updateOpline: function (){
      if (this.diagramOpen == true) {
        let that = this;
        let url = this.urlBase + 'emergency/driver_operate';
        axios.get(url, {
          params: {
            lineCode: that.trainInfo.trains[0],
            trainCode: that.trainInfo.trains[1]
            // isNeedClean="" //非必须  是否需要清除数据
          }
        }).then(function (resp) {
          that.opTimeline = resp.data.result;
        })
            .catch(function (error) {//点击系统时做的操作，如点击“制动系统”、“车门系统”
              //需清空画布
              clearDraw();
              console.log(error)
            });//请求出现错误时回调函数
      }
    },
    //更新节点状态
    getStatus: function () {
      if (this.diagramOpen == true){
        this.getFlowChartData(this.index, this.diagramName);
      }
    },
    registerClick: function (canvas) {
      let that = this;
      canvas.addEventListener('click', function(e){
        //判断点击是否合法
        let node = getClickNode(e);
        if (node.nodeId > 0) {
          that.nodeInfo = node;
          that.msgShow = true;
        }
      }, false);
    },
    chooseStatus: function (key) {
        let that = this;
        let url = this.urlBase + 'emergency/manual_confirm';
        this.msgShow = false;
          axios.post(url,{
              lineCode : that.trainInfo.trains[0],
              trainCode: that.trainInfo.trains[1],
              sceneCode: that.index,
              imageName: that.diagramName,
              nodeId: that.nodeInfo.nodeId,
              manualState : key === true ? 1 : 0
          }).then(function (resp) {
          })
      },
    drawContinue: function (canvas) {
      let that = this;
      if (!this.timer) {
        this.timer = setInterval(function () {
          that.getStatus();
          that.updateOpline();
        }, 1000);
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChange(e) {
      let value = e.target.value;
      let expandedKeys = [];
      if (value == ""){
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        });
        return;
      }

      expandedKeys = dataList
          .map(item => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, this.treeData);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
  },
  created() {

  },
  mounted() {
    let canvas = initCanvas("myCanvas");
    this.drawContinue(canvas);
    //注册点击事件
    this.registerClick(canvas);
    //获取线路目录
    this.getTrainList();

  },
  beforeDestroy() {
    if (this.timer) { //如果定时器还在运行 或者直接关闭，不用判断
      clearInterval(this.timer); //关闭
    }
  }
}
</script>
